<?php

namespace WxWorkSDK\SendMessage\ChatMessage;

use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

class GetChat
{
    const URI = 'appchat/get';
    /**
     * @var string
     * @annotation 调用接口凭证
     */
    public $accessToken = '';
    /**
     * @var string
     * @annotation 群聊id
     */
    public $chatId = '';

    /**
     * GetChat constructor.
     * @param string $accessToken
     * @param string $chatId
     */
    public function __construct(string $accessToken, string $chatId)
    {
        $this->accessToken = $accessToken;
        $this->chatId      = $chatId;
    }

    /**
     * @return Result
     * @annotation
     */
    public function get(): Result
    {
        if ($check = $this->check() != 0) {
            return new Result(FALSE, 1000, $check);
        }
        list($bool, $response) = Http::request('GET', self::URI, ["query" => [
            'chatid'       => $this->chatId,
            'access_token' => $this->accessToken
        ]]);
        if ($bool) {
            return $this->respond($response);
        } else {
            return $response;
        }
    }

    /**
     * @return int|string
     * @annotation
     */
    private function check()
    {
        if (empty($this->token)) {
            return '无access_token';
        }
        if (empty($this->chatId)) {
            return '无群聊id';
        }
        return 0;
    }

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function respond($response): Result
    {
        $response = json_decode($response, TRUE);
        if ($response['errcode'] == 0) {
            return new Result(TRUE, 0, 'ok', $response['chat_info']);
        } else {
            return new Result(FALSE, Error::WX_MISTAKE, $response['errcode'] . ':' . $response['errmsg']);
        }
    }
}